package edu.jmu.dustbinMonitoringSystem.filter;

import edu.jmu.dustbinMonitoringSystem.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Wen
 */
@WebFilter
@Component
public class AuthFilter implements Filter {

    @Autowired
    private RedisService redisService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        String[] urls = {"/login",".js",".css",".ico",".jpg",".png","/reg","/save"};
        boolean flag = true;
        for (String str : urls) {
            if (uri.contains(str)) {
                flag =false;
                break;
            }
        }
        if (!flag) {
            chain.doFilter(request, response);
            return;
        }
        Cookie[] cookies = req.getCookies();
        try {
            for (Cookie c : cookies) {
                if ("token".equals(c.getName())){
                    String value = c.getValue();
                    if (StringUtils.isNoneBlank(redisService.get(value))){
                        String username = redisService.get(value);
                        String[] split = value.split("\\.");
                        String usernameMD5 = DigestUtils.md5DigestAsHex(username.getBytes(StandardCharsets.UTF_8));
                        if (usernameMD5.equals(split[0])){
                            chain.doFilter(request, response);
                            return;
                        }
                    }
                }
            }
            resp.sendRedirect("/login");
        }catch (Exception e){
            resp.sendRedirect("/login");
        }





    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
